package com.awccis.admin.service.impl;

import com.awccis.admin.dao.AdminDao;
import com.awccis.admin.dao.AdminServiceOrderDao;
import com.awccis.admin.model.merchant.MerchantBean;
import com.awccis.admin.model.pay.MerchantNeedPayBean;
import com.awccis.admin.model.pay.MerchantPaDetailInfo;
import com.awccis.admin.model.sorder.ServiceOrderBean;
import com.awccis.admin.model.sorder.ServiceOrderToMerchantBean;
import com.awccis.admin.model.sorder.ServiceTypeBean;
import com.awccis.admin.service.AdminServiceOrderService;
import com.awccis.common.utils.JsonUtil;
import com.awccis.common.utils.PdfUtils;
import com.awccis.common.utils.SendMailToAdmin;
import com.awccis.common.utils.SendMessageUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @author: txp
 * @date: 2018/5/30 on 下午4:13
 * @since: 1.0
 * @description:
 */
@Service("adminServiceOrderService")
public class AdminServiceOrderServiceImpl implements AdminServiceOrderService {

    @Resource
    private AdminServiceOrderDao adminServiceOrderDao;

    @Resource
    private AdminDao adminDao;

    /**
     * 设置merchantInfo
     *
     * @param type         更改类型 insert or update
     * @param merchantBean merchant
     * @return 更改结果
     */
    @Override
    public Boolean setMerchantInfo(String type, MerchantBean merchantBean) {
        boolean result;
        switch (type) {
            case "insert":
                result = adminServiceOrderDao.insertMerchantInfo(merchantBean) == 1;
                break;
            case "update":
                result = adminServiceOrderDao.updateMerchantInfo(merchantBean) == 1;
                break;
            case "delete":
                result = adminServiceOrderDao.deleteMerchantInfo(merchantBean.getMerchantId()) == 1;
                break;
            default:
                result = false;
                break;
        }
        return result;
    }

    /**
     * 根据ID查询商户信息
     *
     * @param merchantId ID
     * @return 商户信息
     */
    @Override
    public MerchantBean getMerchantInfoById(int merchantId) {
        return adminServiceOrderDao.selectMerchantInfoById(merchantId);
    }

    /**
     * 根据类型查询商户信息
     *
     * @param type 类型
     * @return list
     */
    @Override
    public List<MerchantBean> selectMerchantInfoByType(String type) {
        List<MerchantBean> list;
        switch (type) {
            case "all":
                list = adminServiceOrderDao.selectAllMerchantInfo();
                break;
            default:
                list = adminServiceOrderDao.selectMerchantInfoByType(type);
                break;
        }
        return list;
    }

    /**
     * 获取所有service类型
     *
     * @return list
     */
    @Override
    public List<ServiceTypeBean> getAllServiceType() {
        return adminServiceOrderDao.selectAllServiceType();
    }

    /**
     * 添加新的service类型
     *
     * @param serviceTypeBean serviceBean
     * @return 执行结果
     */
    @Override
    public Boolean setNewServiceType(ServiceTypeBean serviceTypeBean) {
        return adminServiceOrderDao.insertServiceType(serviceTypeBean) == 1;
    }

    /**
     * 更改serviceT类型
     *
     * @param serviceTypeBean serviceTypeBean
     * @return 执行结果
     */
    @Override
    public Boolean updateServiceType(ServiceTypeBean serviceTypeBean) {
        return adminServiceOrderDao.updateServiceTypeById(serviceTypeBean) == 1;
    }

    /**
     * 根据ID删除service
     *
     * @param serviceId ID
     * @return 执行结果
     */
    @Override
    public Boolean deleteServiceType(int serviceId) {
        return adminServiceOrderDao.deleteServiceTypeById(serviceId) == 1;
    }

    /**
     * 获取所有预约订单数据
     *
     * @return list列表
     */
    @Override
    public List<ServiceOrderBean> getAllServiceOrder() {
        return adminServiceOrderDao.selectAllServiceOrder();
    }

    /**
     * 添加新的预约订单
     *
     * @param serviceOrderBean serviceOrderBean
     * @return 执行结果
     */
    @Override
    public Boolean setNewServiceOrder(ServiceOrderBean serviceOrderBean) {
        return adminServiceOrderDao.insertServiceOrder(serviceOrderBean) == 1;
    }

    /**
     * 更改预约订单信息
     *
     * @param serviceOrderBean serviceOrderBean
     * @return 执行结果
     */
    @Override
    public Boolean updateServiceOrder(ServiceOrderBean serviceOrderBean) {
        return adminServiceOrderDao.updateServiceOrderById(serviceOrderBean) == 1;
    }

    /**
     * 更改预约订单状态接口
     *
     * @param serviceOrderId
     * @param status
     * @return
     */
    @Override
    public Boolean updateServiceStatus(int serviceOrderId, String status) {
        boolean result;
        switch (status) {
            case "3":
                result = adminServiceOrderDao.updateServiceStatusFinishById(serviceOrderId) == 1;
                break;
            case "-1":
                result = adminServiceOrderDao.updateServiceStatusImpossible(serviceOrderId) == 1;
                break;
            default:
                result = false;
                break;
        }
        return result;
    }

    /**
     * 根据ID删除预约订单信息
     *
     * @param serviceOrderId id
     * @return 执行结果
     */
    @Override
    public Boolean deleteServiceOrder(int serviceOrderId) {
        return adminServiceOrderDao.deleteServiceOrderById(serviceOrderId) == 1;
    }

    /**
     * 根据ID获取预约订单详细信息
     * @param statusId statusId
     * @param serviceOrderId 订单ID
     * @return serviceOrderBean
     */
    @Override
    public ServiceOrderBean getServiceOrderDetailInfo(int statusId, int serviceOrderId) {
        return adminServiceOrderDao.selectServiceOrderInfoById(statusId, serviceOrderId);
    }

    /**
     * 获取不同状态和服务类型的订单
     *
     * @param statusId    状态值
     * @param serviceType 服务类型
     * @return list
     */
    @Override
    public List<ServiceOrderBean> getDiffStatusAndTypeServiceOrder(int statusId, String serviceType) {
        List<ServiceOrderBean> list;
        switch (statusId) {
            case -1:
                list = adminServiceOrderDao.selectServiceOrderByType(-1, serviceType);
                break;
            case 0:
                list = adminServiceOrderDao.selectServiceOrderByType(0, serviceType);
                break;
            case 1:
                list = adminServiceOrderDao.selectServiceOrderByType(1, serviceType);
                break;
            case 2:
                list = adminServiceOrderDao.selectServiceOrderByType(2, serviceType);
                break;
            case 3:
                list = adminServiceOrderDao.selectServiceOrderByType(3, serviceType);
                break;
            default:
                list = new ArrayList<>();
                break;
        }
        return list;
    }

    /**
     * 获取当前周需要付费的商户
     *  1、获取当前周是否已经记录过缴费商户
     *  2、未记录则计算所有需要缴费的商户
     *  3、将所有需要缴费的商户记录在数据库内
     *  4、遍历list对这些商户发送短信和邮件
     *  5、若已经记录过则使用查询出的需要缴费的商户记录，对此list进行4操作
     * @param times 次数
     * @param payWeek 当前周
     * @return list
     */
    @Override
    public List<MerchantPaDetailInfo> getMerchantNeedPay(String times, String payWeek) {

        double exchange = adminDao.selectExchangeRate();
        List<MerchantPaDetailInfo> list;
        //如若是第一次请求，则计算当前需要缴费的商户，否则是直接返回数据库中数据
        if("first".equals(times)){
            list =  adminServiceOrderDao.selectMerchantNeedPay();
        }else {
            list = adminServiceOrderDao.selectMerchantPay(payWeek);
            return list;
        }
        int records = adminServiceOrderDao.selectPayRecordCounts(payWeek);
        if (list.size() > 0) {
            boolean insertResult = false;
            if (records != list.size()){
                List<MerchantNeedPayBean> payList = new ArrayList<>();
                MerchantNeedPayBean merchantNeedPayBean;
                for (MerchantPaDetailInfo merchantPaDetailInfo : list) {
                    merchantNeedPayBean = new MerchantNeedPayBean();
                    merchantNeedPayBean.setMerchantId(merchantPaDetailInfo.getMerchantId());
                    merchantNeedPayBean.setMpayCost(merchantPaDetailInfo.getMpayCost());
                    merchantNeedPayBean.setMpayNeedCost(merchantPaDetailInfo.getMpayNeedCost());
                    merchantNeedPayBean.setMpayWeekOrder(merchantPaDetailInfo.getMpayWeekOrder());
                    merchantNeedPayBean.setMpayWeek(payWeek);
                    payList.add(merchantNeedPayBean);
                }
                System.out.println(payList);
                insertResult = adminServiceOrderDao.insertMerchantPay(payList) == list.size();
            }else {
                list = adminServiceOrderDao.selectMerchantPay(payWeek);
                if (list.size() != records){
                    //return list;
                    System.out.println("当前表内记录与计算结果不匹配！");
                }
            }
            System.out.println("插入商户缴费表：" + insertResult);
            //没有向表中插入数据表示非第一次执行计算缴费记录，直接返回查询的
            if (insertResult){
                Queue<MerchantPaDetailInfo> queue = new LinkedList<>();
                DecimalFormat df = new DecimalFormat("#.00");
                for (MerchantPaDetailInfo mp : list) {
                    sendToMerchant(mp, payWeek, df, exchange, queue);
                }
            }
        } else {
            list = new ArrayList<>();
        }
        return list;
    }

    /**
     * 更改商户缴费记录
     *
     * @param mpayId 缴费记录ID
     * @return 执行结果
     */
    @Override
    public Boolean setMerchantPayRecord(int mpayId) {
        return adminServiceOrderDao.updateMerchantPayStatus(mpayId) == 1;
    }

    /**
     *
     * @param mp
     * @param payWeek
     * @param df
     * @param exchange
     * @param queue
     * @return
     */
    private boolean sendToMerchant(MerchantPaDetailInfo mp, String payWeek, DecimalFormat df, double exchange, Queue queue){
        boolean flag = false;
        String subject = "【AWCCIS】帐单";
        String headMsg = "【AWCCIS】 ";
        String msg = "尊敬的" + mp.getMerchantName()
                + "商户您好，您" + payWeek
                + "的账单已经结算，您本周一共交易" + mp.getMpayWeekOrder()
                + "单，收入" + df.format(mp.getMpayCost())
                + "加元/人民币" + df.format(mp.getMpayCost() * exchange)
                + "元,您本周需要支付平台费用" + df.format(mp.getMpayNeedCost())
                + "加元/人民币" + df.format(mp.getMpayNeedCost() * exchange)
                +"元。";
        String mailMsg = "详细信息已经发送至您的邮箱中，敬请及时查看。";
        String endMsg = "感谢您的使用。";
        String hintMsg = "本周的详细订单以及缴费须知，请查看邮件中的附件。";
        System.out.println(msg + endMsg);
        //String s = SendMessageUtil.sendMessageTo(mp.getMerchantPhone(), headMsg+msg+endMsg+mailMsg);
        //System.out.println("发送短信：" + s);

        List<ServiceOrderToMerchantBean> somList = adminServiceOrderDao.selectMerchantSimpleOrderInWeek(mp.getMerchantId());
        String fileName = JsonUtil.getJsonConfigValue("pdf") +payWeek+mp.getMerchantName()+".pdf";

        Map data = PdfUtils.initData(payWeek+"账单",msg , somList);
        PdfUtils.detailsToPdf(fileName, data,"+17785131013","VanLazyLife");
        try {
            File file = new File(fileName);
            if(file.exists()){
                boolean sendTextEmail = SendMailToAdmin.sendTextEmail(mp.getMerchantMail(), subject, msg + "\n" + hintMsg + "\n" + endMsg,true,fileName);
                if (!sendTextEmail){
                    queue.offer(mp);
                }else {

                }
                System.out.println(true);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return false;
    }

}
